<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    td,
    th {
      border: 1px solid #000;
    }

    table {
      margin-top: 30px;
      width: 500px;
      border-collapse: collapse;
    }
  </style>
</head>

<body>
  <input type="text" class="bookname" placeholder="图书名">
  <input type="text" class="author" placeholder="作者">
  <button class="add">添加</button>
  <table>
    <thead>
      <tr>
        <th>编号</th>
        <th>图书名</th>
        <th>作者</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    let tbody = document.querySelector('tbody')
    let add = document.querySelector('.add')
    let bookname = document.querySelector('.bookname')
    let author = document.querySelector('.author')
    add.addEventListener('click', function () {
      if (bookname.value.trim() && author.value.trim()) {
        axios.post('http://localhost:3000/books', {
          bookname: bookname.value,
          author: author.value
        })
          .then(res => {
            if(res.status === 200) {
              render()
            }
          })
          .catch(err => {
            console.error(err);
          })

      } else {
        alert('书名和作者不能为空')
      }
    })

    tbody.addEventListener('click', function (e) {
      if(e.target.nodeName === 'A') {
        axios.delete('http://localhost:3000/books?id=' + e.target.dataset.id)
        .then(res => {
          if(res.status === 200) {
            render()
          }
        })
        .catch(err => {
          console.error(err);
        })
      }
    })
    function render() {
      axios.get('http://localhost:3000/books')
        .then(res => {
          let str = ''
          res.data.forEach(item => {
            str += `
              <tr>
                <td>${item.id}</td>
                <td>${item.bookname}</td>
                <td>${item.author}</td>
                <td>
                  <a data-id=${item.id} href="#">删除</a>
                </td>
              </tr>
              `
          });
          tbody.innerHTML = str
        })
        .catch(err => {
          console.error(err);
        })
    }
    render()
  </script>
</body>

</html>